/*
 * Copyright (C), 2002-2013, 你的兔宝宝电子商务有限公司
 * FileName: ParseObject2Xml.java
 * Author:   10074771
 * Date:     2013-10-4 下午5:45:15
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.baby.demo.utils;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 〈Java对象转换成Xml对象〉<br>
 * 〈该类源码从sop-util包获取〉
 * 
 * @author 12074565
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class ParseObject2Xml {

    private static final Logger LOGGER = LoggerFactory.getLogger(ParseObject2Xml.class);
    
    private Document doc = null;

    /**
     * 得到Document对象
     * 
     * @param xmlStr
     * @return
     * @throws DocumentException
     */
    public Document createDocument() throws DocumentException {
        doc = DocumentHelper.createDocument();
        return doc;
    }

    /**
     * 以字符串形式获取document
     * 
     * @return
     * @throws IOException
     */
    public String getMsg() throws IOException {
        XMLWriter xmlWriter = null;
        StringWriter writer = new StringWriter();
        xmlWriter = new XMLWriter(writer);
        xmlWriter.write(doc);
        return writer.toString();
    }

    /**
     * 以字符串形式获取document
     * 
     * @return
     * @throws IOException
     */
    public String getMsg2(Map<?, ?> data) {
        Document odoc = DocumentHelper.createDocument();
        XMLWriter xmlWriter = null;
        StringWriter writer = new StringWriter();

        try {
            parser2(data, odoc);
            xmlWriter = new XMLWriter(writer);
            xmlWriter.write(odoc);
            xmlWriter.flush();
        } catch (IOException e) {
            LOGGER.error("getMsg2 " + e.getMessage(),e);
        } catch (IllegalArgumentException e) {
            LOGGER.error("getMsg2 IllegalArgumentException " + e.getMessage(),e);
        } catch (DocumentException e) {
            LOGGER.error("getMsg2 DocumentException " + e.getMessage(),e);
        } finally {
            if (xmlWriter != null) {
                try {
                    xmlWriter.close();
                } catch (IOException e) {
                    LOGGER.error("xmlWriter close" + e.getMessage(),e);
                }
            }
            try {
                writer.close();
            } catch (IOException e) {
                LOGGER.error("writer close" + e.getMessage(),e);
            }
        }
        return writer.toString();
    }

    /**
     * 将java对象转换成xml格式数据
     * 
     * @param data
     * @throws IllegalArgumentException
     * @throws DocumentException
     */
    public void parser2(Map<?, ?> data, Document doc) throws DocumentException {
        // 非法格式数据
        if (1 < data.size()) {
            throw new IllegalArgumentException();
        }

        // 创建document
        Element root = null;
        String rootKey = "";
        Iterator<?> it = data.entrySet().iterator();

        while (it.hasNext()) {
            Entry<?, ?> entry = (Entry<?, ?>) it.next();
            rootKey = (String) entry.getKey();
            root = doc.addElement(rootKey);

        }
        if( root != null){
            if (data.get(rootKey) instanceof String) {
                root.setText(data.get(rootKey).toString());
            } else {
                nestParse(root, (Map<?, ?>) data.get(rootKey));
            }
        }
    }

    /**
     * 将java对象转换成xml格式数据
     * 
     * @param data
     * @throws IllegalArgumentException
     * @throws DocumentException
     */
    public void parser(Map<?, ?> data) throws DocumentException {
        // 非法格式数据
        if (1 < data.size()) {
            throw new IllegalArgumentException();
        }

        // 创建document
        createDocument();

        Element root = null;
        String rootKey = "";
        Iterator<?> it = data.entrySet().iterator();

        while (it.hasNext()) {
            Entry<?, ?> entry = (Entry<?, ?>) it.next();
            rootKey = (String) entry.getKey();
            root = doc.addElement(rootKey);
        }
        if( root != null){
            if (data.get(rootKey) instanceof String) {
                root.setText(data.get(rootKey).toString());
            } else {
                nestParse(root, (Map<?, ?>) data.get(rootKey));
            }
        }
    }

    /**
     * 将java对象转换成xml格式数据
     * 
     * @param root
     * @param data
     */
    public void nestParse(Element root, Map<?, ?> data) {
        Map<?, ?> dataMap = (Map<?, ?>) data;
        String key = "";
        Iterator<?> it = dataMap.entrySet().iterator();

        while (it.hasNext()) {
            Entry<?, ?> entry = (Entry<?, ?>) it.next();
            key = (String) entry.getKey();
            Object value = entry.getValue();

            if (value instanceof Map) {
                // 嵌套元素
                Element element = root.addElement(key);
                nestParse(element, (Map<?, ?>) value);
            } else if (value instanceof List) {
                // repeate元素
                List<?> valList = (List<?>) value;
                for (int i = 0; i < valList.size(); i++) {
                    Element element = root.addElement(key);
                    if (valList.get(i) instanceof String) {
                        element.setText(valList.get(i).toString());
                    } else if (valList.get(i) instanceof Map) {
                        nestParse(element, (Map<?, ?>) valList.get(i));
                    }
                }
            } else {
                Element element = root.addElement(key);
                if (!Strings.isEmpty(value)) {
                    element.setText(value.toString());
                } else {
                    element.setText("");

                }
            }
        }
    }
}
